package com.tykboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.tykboot.core.base.BaseController;
import com.tykboot.message.ResponseMsg;
import com.tykboot.service.IAuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * TestController类
 *
 * @author LiuYu
 * @date 2018/07/30
 */
@RestController
@RequestMapping("/auth")
public class AuthController extends BaseController {

    @Autowired
    private IAuthService authService;

    @PostMapping("/login")
    public ResponseMsg login(@RequestBody JSONObject request) {
        ResponseMsg responseMsg = new ResponseMsg();
        String userName = request.getString("userName");
        String password = request.getString("password");
        String token = authService.login(userName, password);
        if (StringUtils.isBlank(token)) {
            return new ResponseMsg(-1, "账号或密码错误");
        }
        responseMsg.setData(token);
        return responseMsg;
    }

    @PostMapping("/logout")
    public ResponseMsg logout() {
        ResponseMsg responseMsg = new ResponseMsg();
        String token = getTokenFromHeader();
        if (StringUtils.isBlank(token)) {
            return new ResponseMsg();
        }
        authService.logout(token);
        return responseMsg;
    }

    @PostMapping("/refreshToken")
    public ResponseMsg refreshToken() {
        ResponseMsg responseMsg = new ResponseMsg();
        String token = getTokenFromHeader();
        if (StringUtils.isBlank(token)) {
            return new ResponseMsg();
        }
        authService.logout(token);
        return responseMsg;
    }


}